//
//  NiceQueueViewController.m
//  HappyTrip
//
//  Created by dlios on 15-3-28.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "NiceQueueViewController.h"
#import "NiceQueueCollectionViewCell.h"
#import "UIImageView+AFNetworking.h"
#import "TravelNoteViewController.h"
// 刷新加载
#import "MJRefresh.h"


@interface NiceQueueViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) NSMutableArray *itemsArr;
@property (nonatomic, retain) UICollectionView *collectionView;

@end

@implementation NiceQueueViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
//    self.tabBarController.tabBar.hidden = NO;
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    self.title = @"精选图片";
    self.itemsArr = [NSMutableArray array];
    [self handleData:0];
    self.collectionView.bounces = YES;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width / 2 - 15, self.view.frame.size.width / 2 - 15);
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 10, 10, 10);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    // 添加一个人轻扫手势
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
    [self.collectionView addGestureRecognizer:swipe];
    [self.view addSubview:self.collectionView];
    [swipe release];
    [flowLayout release];
    
    // 注册重用池
    [self.collectionView registerClass:[NiceQueueCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [_collectionView release];
    
    //刷新加载
    [self.collectionView addLegendHeaderWithRefreshingBlock:^{
//        self.itemsArr = [NSMutableArray array];
//        [self handleData:0];
        [self.collectionView.header endRefreshing];
        NSLog(@"123456789");
    }];
    [self.collectionView addLegendFooterWithRefreshingBlock:^{
        static NSInteger i = 1;
        [self handleData:i++ * 12];
    }];

    [self.collectionView.footer beginRefreshing];
}
// collectionView协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.itemsArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NiceQueue *niceQueue = [self.itemsArr objectAtIndex:indexPath.item];
    NiceQueueCollectionViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
//    cell.imageView.hidden = YES;
    NSLog(@"++++++++++++%ld", indexPath.item);
    cell.niceQueue = niceQueue;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NiceQueue *niceQueue = [self.itemsArr objectAtIndex:indexPath.item];
    TravelNoteViewController *travVC = [[TravelNoteViewController alloc] init];
    travVC.transmitId = niceQueue.trip_id;
    NSLog(@"trip_id%@", niceQueue.trip_id);
    travVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:travVC animated:YES];
    [travVC release];
}

- (void)swipeAction:(UISwipeGestureRecognizer *)swipe
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)leftBarButtonItemAction:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 数据请求
- (void)handleData:(NSInteger)startNumber
{
    NSString *urlStr = [NSString stringWithFormat:@"http://api.breadtrip.com/featured/photos/?start=%ld&count=12", startNumber];
    NSLog(@"_+_+_+_+_+_+%@00000000\n", urlStr);
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.happyTripDestination", docPath, [urlStr hash]];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:path];
        NSLog(@"存储成功: %d", result);
        NSLog(@"%@", path);
        NSDictionary *array = [responseObject objectForKey:@"items"];
        for (NSDictionary *dic in array) {
            NiceQueue *niceQueue = [[NiceQueue alloc] initWithDictionary:dic];
            [self.itemsArr addObject:niceQueue];
            [niceQueue release];
//            NSLog(@"self.tripsArr %@", self.itemsArr);
        }
        [self.collectionView reloadData];
        
        //刷新加载
//        if (self.itemsArr.count > 12) {
//        }
        [self.collectionView.footer endRefreshing];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        id resultID = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSLog(@"result: %@", resultID);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
